from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session

from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blue
from info.models import User, News, Category
from info import constants


@index_blue.route('/newslist')
def get_news_list():
    # get请求用args取参数
    args_dict = request.args
    cid = args_dict.get('cid', '1')
    page = args_dict.get('page', '1')
    per_page = args_dict.get('per_page', 10)

    # 2. 校验参数
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    filters = [News.status == 0]
    # # 如果分类id不为0，那么添加分类id的过滤
    # if cid != "0":
    #     filters.append(News.category_id == cid)
    if cid != '1':
        filters.append(News.category_id == cid)
    paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)

    current_page = paginate.page
    totals_page = paginate.pages
    # 取当前页数据对象
    news_list = paginate.items

    news_dict_list = []
    for new in news_list:
        # 转换成字典
        news_dict_list.append(new.to_basic_dict())

    data = {
        'current_page': current_page,
        'totals_page': totals_page,
        'news_dict_list': news_dict_list
    }

    # 4. 返回数据
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@index_blue.route('/')
@user_login_data
def index():
    # 通过session获取用户id

    # user_mobile = session.get('mobile')
    #
    # user = None
    # if user_mobile:
    #     try:
    #         # 通过id来查询用户信息，是个对象
    #         user = User.query.filter(User.mobile == user_mobile).first()
    #     except Exception as e:
    #         current_app.logger.error(e)

    # current_app.logger.debug(data)
    # current_app.logger.error('error')

    user = g.user

    new_list = None

    try:
        # 取出排名前十的新闻对象
        new_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    click_new_list = []
    for new in new_list:
        click_new_list.append(new)
    current_app.logger.debug('新闻列表')
    current_app.logger.debug(click_new_list)

    # 获取新闻分类数据
    categories = Category.query.all()
    # 定义列表保存分类数据
    categories_dicts = []

    for category in categories:
        # 拼接内容
        categories_dicts.append(category.to_dict())

    data = {
        'user_info': user.to_dict() if user else None,
        'click_news_list': click_new_list,
        "categories": categories_dicts
    }

    return render_template('news/index.html', data=data)


@index_blue.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')